'use strict';

var pool = require('./pool.js');
var utils = require('../utils/utils.js');

var service = exports = module.exports = {};


service.lowChangeData = function(){
	initEmoCategory();	
	initDictumCategory();
	initHotCat();	
	initHotDicCat();
	initAvatar();
	initBubble();
	initPaper();
	
	initFont();
	initColor();
}

service.init = function(){
	initEmoFeed();
	
	initEmoCateMap();	
	initBanner();
	
	initParam();
	initAppKey();	
	
	initDictumFeed()	
	initDictumCateMap();

	
}

service.bigDataCache = function(){
	initEmoticon();
	initDictum();
}

function initEmoFeed(){
		pool.acquire().then(function( connection) {			
	    connection.query("select f.title,f.subTitle,f.icon,f.clickUrl,i.title as ititle,i.subscript,e.* from emoFeed f,emoItem i,emoticon e where f.deleted=0 and f.locked=0 and f.id=i.emoFeed_id and i.deleted=0 and i.emoticon_id=e.id order by f.serialNo,i.serialNo" ,
	     function(err,res,fields) {
	     	var emoFeed =[];
	     	if(res && res.length > 0){
					var lastType='';
					var lastFeed={};
	     		for(var i=0; i<res.length; i++){  
	   				
	   				var it = res[i];
	   				if(it.title != lastType){
	   					lastFeed = {};
	   					lastType = it.title;
	   					emoFeed.push(lastFeed)
	   					lastFeed.title=it.title;
	   					lastFeed.subTitle=it.subTitle;
	   					lastFeed.icon=it.icon;
	   					lastFeed.clickUrl=it.clickUrl;
	   					lastFeed.items=[];
	   				}
	   				var emo = {};
	   				emo.id=it.id;
	   				emo.title=it.title;
	   				emo.thumb=global.config.imgPath + it.thumb;
	   				emo.fileName=global.config.imgPath + it.fileName;
	   				emo.gif=it.gif;
	
	   				lastFeed.items.push(emo);
	            
	         }	
	      	
	     	}
	     	global.emoticonCache.emoFeed=emoFeed;
	     	pool.release(connection);
	    });
		});
}
function initEmoticon(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select * from emoticon where deleted=0" ,
	     function(err,res,fields) {
	     	var emoticons =[];
	     	var subCats={};
	     	var emoPkey={};
	     	if(res && res.length > 0){
	
	     		for(var i=0; i<res.length; i++){  
	   				var emo = {};
	   				var it = res[i];
	   				emo.id=it.id;
	   				emo.fileName=it.fileName;
	   				emo.fontSize=it.fontSize;
	   				emo.x=it.x;
	   				emo.y=it.y;
	   				emo.width=it.width;
	   				emo.height=it.height;
	   				emo.lineLimit=it.lineLimit;
	   				
	   				emo.gif=it.gif;
	   				emo.border=it.border;
	   	
	   				emo.thumb=it.thumb;
	   				emo.frames=it.frames;
	   				emo.frameStr=it.frameStr;

	   				emo.tags=it.tags;
	   				emo.catIds=it.catIds;
	   				emo.tagIds=it.tagIds;  				
	   				emoticons.push(emo);
	   				emoPkey[it.id] = i
	   				if(emo.tagIds){
	   					var ids = emo.tagIds.split(",")
	   					for(var j=0;j<ids.length;j++){
	   						if(!ids[j]) continue;
	   						var scat = subCats[ids[j]]
	   						if(!scat){
	   							scat=[]
	   							subCats[ids[j]] = scat
	   						}
	   						scat.push(emo)
	   					}
	   				}
	            
	         }	
	      	
	     	}
	     	global.emoticonCache.emoticons=emoticons;     	
	     	global.emoticonCache.subCats=subCats;
	     	global.emoticonCache.emoPkey=emoPkey;
	     	pool.release(connection);
	    });
		});
}


function initEmoCategory(){	
		pool.acquire().then(function( connection) {			
	    connection.query("select * from emocategory where deleted=0 and level=1 order by serialNo" ,
	     function(err,res,fields) {
	     	var cats =[];
	     	if(res && res.length > 0){	     
     		
	     		for(var i=0; i<res.length; i++){  
	   				var cat = {};
	   				var it = res[i];
	   				cat.name=it.name;
	   				cat.id=it.id;
	          cats.push(cat) 
	         }	     	
	     	}
	     	global.emoticonCache.emoCats=cats;
	     	pool.release(connection);
	    });
		});
}

function initEmoCateMap(){	
		pool.acquire().then(function( connection) {			
	    connection.query("select c.id,c.parent_id,c.name,e.id as eid,e.thumb,e.gif,e.fileName from EmoCategory c left join emoticon e on e.showCat_id = c.id where c.level=2 order by c.parent_id,c.serialNo" ,
	     function(err,res,fields) {
	     	var cats ={};
	     	var pcat={id:'0'};
	     	var scat={id:'0'};
	     	if(res && res.length > 0){	     
     		
	     		for(var i=0; i<res.length; i++){ 
	     			var it = res[i]; 
	     			if(pcat.id != it.parent_id){
	     				pcat={}
	     				pcat.id = it.parent_id;
	     				pcat.items=[];
	     				cats[it.parent_id] = pcat;
	     			}
	     			if(scat.id != it.id){
	     				scat={}
	     				scat.id=it.id
	     				scat.title=it.name
	     				scat.items=[];
	     				pcat.items.push(scat)
	     			}
	     			
	     			
	   				var emo = {};
	   				
	   				emo.thumb=global.config.imgPath + it.thumb;
	   				emo.fileName=global.config.imgPath + it.fileName;
	   				emo.gif=it.gif;
	   				emo.id=it.eid;
	   				scat.items.push(emo)
	            
	         }	     	
	     	}
	     	global.emoticonCache.emoCatsMap=cats;
	     	
	     	pool.release(connection);
	    });
		});
}

function initParam(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select * from param where deleted=0 and locked=0 " ,
	     function(err,res,fields) {
	     	var param={}
	     	if(res && res.length > 0){
	     		
	     		for(var i=0; i<res.length; i++){  
	   				var hot = {};
	   				var it = res[i];
	   				if(it.type == 'emoTag' || it.type == 'dicTag'){
	   					param[it.type] = it.value.split(',')
	   				}else{
	   					param[it.type] = it.value
	   				}
	         }		      	
	     	}
	     	global.emoticonCache.param=param;
	     	pool.release(connection);
	    });
		});
}

function initHotCat(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select h.serialNo,e.name,e.id from hotcat h,emocategory e where h.deleted=0 and h.emoCategory_id=e.id  order by h.serialNo " ,
	     function(err,res,fields) {
	     	var hotKeys =[];
	     	if(res && res.length > 0){
	     		
	     		for(var i=0; i<res.length; i++){  
	   				var hot = {};
	   				var it = res[i];
	   				hot.id=it.id;
	   				hot.name=it.name;
	          hotKeys.push(hot);
	         }		      	
	     	}
	     	global.emoticonCache.hotCat=hotKeys;
	     	pool.release(connection);
	    });
		});
}


function initBanner(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select * from Banner where deleted=0 and locked=0 and beginDate <= CURDATE() and endDate > CURDATE() order by position " ,
	     function(err,res,fields) {
	     	var banners =[];
	     	var posMap=null;
	     	if(res && res.length > 0){
	     		
	     		var lastPosition=0;
	     		for(var i=0; i<res.length; i++){  
	   				var banner = {};
	   				var it = res[i];
	   				
	   				banner.title=it.title;
	          banner.img=global.config.basePath +it.img; 
	          banner.type=it.type; 
	          banner.clickUrl=it.clickUrl; 
	          banner.position=it.position;
	          
	          if(it.position != lastPosition){
	          	posMap={}
	          	posMap.list=[]
	          	banners.push(posMap)
	          }
	          
	          posMap.list.push(banner)
	       
	          lastPosition =  it.position; 
	        }		      	
	     	}
	     	global.emoticonCache.banners=banners;
	     	pool.release(connection);
	    });
		});
}

function initAppKey(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select * from appKey where deleted=0  " ,
	     function(err,res,fields) {
	     	var appKeys ={};
	     	if(res && res.length > 0){
	     		
	     		for(var i=0; i<res.length; i++){  
	   				var key = {};
	   				var it = res[i];
	   				key.version=it.version;
	          key.hardKey=it.hardKey;  
	          key.softKeys=it.softKeys.split(',');  
	          key.shadowKeys=it.shadowKeys.split(',');  
	          appKeys[it.version+''] = key;
	          
	          var md5Key={}
	          var keyAry =  key.softKeys
	          for(var j=0;j<keyAry.length;j++){
	          	
	          	md5Key[utils.digest(keyAry[j])] = keyAry[j]
	          }
	          key.md5=md5Key
	            
	        }		      	
	     	}
	     	global.emoticonCache.appKeys=appKeys;
	     	pool.release(connection);
	    });
		});
}

function initDictumFeed(){
		pool.acquire().then(function( connection) {			
	    connection.query("select f.title,f.subTitle,f.icon,f.clickUrl,i.title as ititle,i.subscript,e.*,a.name as author,a.dynasty from dictumFeed f join dictumItem i on f.id=i.dictumFeed_id join dictum e on i.dictum_id=e.id left join author a on a.id=e.author_id where f.deleted=0 and f.locked=0  and i.deleted=0  order by f.serialNo,i.serialNo" ,
	     function(err,res,fields) {
	     	var dictumFeed =[];
	     	if(res && res.length > 0){
					var lastType='';
					var lastFeed={};
	     		for(var i=0; i<res.length; i++){  
	   				
	   				var it = res[i];
	   				if(it.title != lastType){
	   					lastFeed = {};
	   					lastType = it.title;
	   					dictumFeed.push(lastFeed)
	   					lastFeed.title=it.title;
	   					lastFeed.subTitle=it.subTitle;
	   					lastFeed.icon=it.icon;
	   					lastFeed.clickUrl=it.clickUrl;
	   					lastFeed.items=[];
	   				}
	   				var dictum = {};
	   				dictum.id=it.id;
	   				dictum.name=it.name;
	   				dictum.content=it.content;
	   				dictum.author=it.author;
	   				dictum.dynasty=it.dynasty;
	
	   				lastFeed.items.push(dictum);
	            
	         }	
	      	
	     	}
	     	global.emoticonCache.dictumFeed=dictumFeed;
	     	pool.release(connection);
	    });
		});
}
function initDictum(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select e.id,e.name,e.content,e.cipai,e.catIds,e.tagIds,e.tags,e.type,a.name as author,a.dynasty from dictum e left join author a on a.id=e.author_id where e.deleted=0" ,
	     function(err,res,fields) {
	     	var dictums =[];
	     	var subDicCats={};
	     	var dictumPkey={};
	     	if(res && res.length > 0){
	
	     		for(var i=0; i<res.length; i++){  
	   				var dictum = {};
	   				var it = res[i];
	   				dictum.id=it.id;
	   				dictum.name=it.name;
	   				dictum.content=it.content;
	   				dictum.cipai=it.cipai;
	   				dictum.catIds=it.catIds;
	   				dictum.tagIds=it.tagIds;
	   				dictum.tags=it.tags;
	   				dictum.type=it.type;
	   				
	   				dictum.author=it.author;
	   				dictum.dynasty=it.dynasty;
	   	
	   						
	   				dictums.push(dictum);
	   				dictumPkey[it.id] = i
	   				if(dictum.tagIds){
	   					var ids = dictum.tagIds.split(",")
	   					for(var j=0;j<ids.length;j++){
	   						if(!ids[j]) continue;
	   						var scat = subDicCats[ids[j]]
	   						if(!scat){
	   							scat=[]
	   							subDicCats[ids[j]] = scat
	   						}
	   						scat.push(dictum)
	   					}
	   				}
	            
	         }	
	      	
	     	}
	     	global.emoticonCache.dictums=dictums;     	
	     	global.emoticonCache.subDicCats=subDicCats;
	     	global.emoticonCache.dictumPkey=dictumPkey;
	     	console.log(dictums.length)
	     	pool.release(connection);
	    });
		});
}


function initDictumCategory(){	
		pool.acquire().then(function( connection) {			
	    connection.query("select * from dictumCategory where deleted=0 and level=1 and (locked=0 or locked is null) order by serialNo" ,
	     function(err,res,fields) {
	     	var cats =[];
	     	if(res && res.length > 0){	     
     		
	     		for(var i=0; i<res.length; i++){  
	   				var cat = {};
	   				var it = res[i];
	   				cat.name=it.name;
	   				cat.id=it.id;
	          cats.push(cat) 
	         }	     	
	     	}
	     	global.emoticonCache.dictumCats=cats;
	     	pool.release(connection);
	    });
		});
}

function initDictumCateMap(){	
		pool.acquire().then(function( connection) {			
	    connection.query("select c.id,c.parent_id,c.name as tname ,e.name,e.id as eid,e.content,a.name as author,a.dynasty from dictumCategory c left join dictum e on e.showCat_id = c.id left join author a on a.id=e.author_id  where c.level=2 and (c.locked=0 or c.locked is null) order by c.parent_id,c.serialNo" ,
	     function(err,res,fields) {
	     	var cats ={};
	     	var pcat={id:'0'};
	     	var scat={id:'0'};
	     	if(res && res.length > 0){	     
     		
	     		for(var i=0; i<res.length; i++){ 
	     			var it = res[i]; 
	     			if(pcat.id != it.parent_id){
	     				pcat={}
	     				pcat.id = it.parent_id;
	     				pcat.items=[];
	     				cats[it.parent_id] = pcat;
	     			}
	     			if(scat.id != it.id){
	     				scat={}
	     				scat.id=it.id
	     				scat.title=it.tname
	     				scat.items=[];
	     				pcat.items.push(scat)
	     			}
	     			if(!it.eid) continue;
	     			
	   				var dictum = {};
	   				
	   				dictum.dynasty=it.dynasty;
	   				dictum.author=it.author;
	   				dictum.content=it.content;
	   				dictum.name=it.name;
	   				dictum.id=it.eid;
	   				scat.items.push(dictum)
	            
	         }	     	
	     	}
	     	global.emoticonCache.dictumCatsMap=cats;
	     	
	     	pool.release(connection);
	    });
		});
}
function initHotDicCat(){
	
		pool.acquire().then(function( connection) {
			
	    connection.query("select h.serialNo,e.name,e.id from hotDicCat h,dictumCategory e where h.deleted=0 and h.dictumCategory_id=e.id  order by h.serialNo " ,
	     function(err,res,fields) {
	     	var hotKeys =[];
	     	if(res && res.length > 0){
	     		
	     		for(var i=0; i<res.length; i++){  
	   				var hot = {};
	   				var it = res[i];
	   				hot.id=it.id;
	   				hot.name=it.name;
	            
	            hotKeys.push(hot);
	         }		      	
	     	}
	     	global.emoticonCache.hotDicCat=hotKeys;
	     	pool.release(connection);
	    });
		});
}

function initAvatar(){
	pool.acquire().then(function( connection) {
			
	    connection.query("select t.name as tname,a.name,a.fileName,a.kind,a.width,a.height from avatar a,avatarType t where a.deleted=0 and a.locked=0 and t.deleted=0 and t.locked=0 and a.avatarType_id=t.id  order by a.serialNo " ,
	     function(err,res,fields) {
	     	var btypes =[];
	     	var ptypes =[];
	     	
	     	if(res && res.length > 0){
	     		//var lastType=""
	     		//var btype=null;
	     		//var ptype=null;
	     		for(var i=0; i<res.length; i++){  
	   				var obj = {};
	   				var it = res[i];
	   				
	   				//if(it.tname != lastType){
	   				//	btype={}
	   				//	btype.name = it.tname
	   				//	btype.items=[];
	   					
	   				//	ptype={}
	   				//	ptype.name = it.tname
	   				//	ptype.items=[];
	   					
	   				//	btypes.push(btype)
	   				//	ptypes.push(ptype)
	   				//}
	   				//lastType = it.tname
	   				
	   				obj.name=it.name;
	   				obj.width=it.width;
	   				obj.height=it.height;
	   				obj.fileName=global.config.basePath +it.fileName;
	          if(it.kind=='paper' || it.kind=='all')
	            ptypes.push(obj);
	          if(it.kind=='bubble' || it.kind=='all')
	          	btypes.push(obj);
	         }		      	
	     	}
	     	global.emoticonCache.bubbleAvatars=btypes;
	     	global.emoticonCache.paperAvatars=ptypes;
	     	pool.release(connection);
	    });
		});
	
}
function initBubble(){
	pool.acquire().then(function( connection) {
			
	    connection.query("select t.name as tname,a.* from bubble a,bubbleType t where a.deleted=0 and a.locked=0 and t.deleted=0 and t.locked=0 and a.bubbleType_id=t.id  order by a.serialNo" ,
	     function(err,res,fields) {
	     	var types =[];
	     	if(res && res.length > 0){
	     		//var lastType=""
	     		//var type=null;
	     		for(var i=0; i<res.length; i++){  
	   				var obj = {};
	   				var it = res[i];
	   				
	   				//if(it.tname != lastType){
	   				//	type={}
	   				//	type.name = it.tname
	   				//	type.items=[];
	   				//	types.push(type)
	   				//}
	   				//lastType = it.tname
	   				
	   				obj.name=it.name;
	   				obj.file1=global.config.basePath +it.path +"/1.png";
	   				obj.file2=global.config.basePath +it.path +"/2.png";
	   				obj.file3=global.config.basePath +it.path +"/3.png";
	   				obj.file4=global.config.basePath +it.path +"/4.png";
	   				obj.width=it.width;
	   				obj.height1=it.height1;
	   				obj.height2=it.height2;
	   				obj.height3=it.height3;
	   				obj.height4=it.height4;
	   				obj.showAvatar=it.showAvatar;
	   				if(obj.showAvatar == 1){
	   					obj.avatarHeight=it.avatarHeight;
	   					obj.avatarBottom=it.avatarBottom;
	   					obj.avatarRight=it.avatarRight;
	   				}
	            
	            types.push(obj);
	         }		      	
	     	}
	     	global.emoticonCache.bubbles=types;
	     	pool.release(connection);
	    });
		});
}
function initPaper(){
	pool.acquire().then(function( connection) {
			
	    connection.query("select t.name as tname,a.name,a.thumb,a.fileName,a.showAvatar from paper a,paperType t where a.deleted=0 and a.locked=0 and t.deleted=0 and t.locked=0 and a.paperType_id=t.id  order by a.serialNo " ,
	     function(err,res,fields) {
	     	var types =[];
	     	
	     	if(res && res.length > 0){
	     		//var lastType=""
	     		//var type=null;
	     		for(var i=0; i<res.length; i++){  
	   				var obj = {};
	   				var it = res[i];
	   				
	   				//if(it.tname != lastType){
	   				//	type={}
	   				//	type.name = it.tname
	   				//	type.items=[];
	   				//	types.push(type)
	   				//}
	   				//lastType = it.tname
	   				
	   				obj.name=it.name;
	   				obj.thumb=global.config.basePath +it.thumb;
	   				obj.fileName=global.config.basePath +it.fileName;
	   				obj.showAvatar=it.showAvatar
	            
	            types.push(obj);
	         }		      	
	     	}
	     	global.emoticonCache.papers=types;
	     	pool.release(connection);
	    });
		});
}


function initFont(){
	pool.acquire().then(function( connection) {
			
	    connection.query("select name,code,fileName from font  where deleted=0  order by serialNo " ,
	     function(err,res,fields) {
	     	var fonts =[];
	     	
	     	if(res && res.length > 0){
	     
	     		for(var i=0; i<res.length; i++){  
	   				var obj = {};
	   				var it = res[i];
	   			
	   				
	   				obj.name=it.name;
	   				obj.fileName=global.config.basePath +it.fileName;
	   				obj.code=it.code
	          fonts.push(obj);
	         }		      	
	     	}
	     	global.emoticonCache.fonts=fonts;
	     	pool.release(connection);
	    });
		});
}

function initColor(){
	pool.acquire().then(function( connection) {
			
	    connection.query("select id,name,bcolor,color,fileName from colorSet  where deleted=0  order by serialNo " ,
	     function(err,res,fields) {
	     	var colors =[];
	     	
	     	if(res && res.length > 0){
	     
	     		for(var i=0; i<res.length; i++){  
	   				var obj = {};
	   				var it = res[i];
	   			
	   				
	   				obj.name=it.name;
	   				obj.fileName=global.config.basePath +it.fileName;
	   				obj.color=it.color
	   				obj.bcolor=it.bcolor
	   				obj.code=it.id
	          colors.push(obj);
	         }		      	
	     	}
	     	global.emoticonCache.colors=colors;
	     	pool.release(connection);
	    });
		});
}

